<?php
/**
 * Created by PhpStorm.
 * User: zhaoyi
 * Date: 2022/1/26
 * Time: 11:46.
 */

declare(strict_types=1);

namespace App\Application\Api\Controller;

use App\Annotation\Api;
use App\Application\Admin\Model\Order;
use App\Application\Admin\Model\Package;
use App\Application\Admin\Model\Room;
use App\Application\Admin\Model\CouponMember;
use App\Application\Admin\Model\Roomlabel;
use App\Application\Admin\Model\Store;
use App\Application\Admin\Service\AdminSettingService;
use App\Application\Admin\Service\CityService;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Controller;
use function Symfony\Component\Translation\t;

#[Controller("/api/order")]
class OrderController extends AbstractController
{
    #[Inject]
    protected AdminSettingService $setting;

    #[Api]
    #[PostMapping("add")]
    function add()
    {
        $package_id = $this->request->input('package_id', '');
        $room_id = $this->request->input('room_id', '');
        $store_id = $this->request->input('store_id', '');
        $add_time = $this->request->input('add_time', '');
        $end_time = $this->request->input('end_time', '');
        // 查询当前是否预约

        $order = Order::where('room_id', $room_id)->whereIn('status', [0, 1, 6])->select('*')
            ->orderBy('created_at', 'asc')
            ->get()->toArray();
        $where = [];
        $where[] = ['package_id', '=', $package_id];
        $package = Package::where($where)
            ->select('*')
            ->first() ?: [];
        $orderStatus = 0;
        foreach ($order as $i => $v) {
            $add_hour = $v['add_time'];
            $end_hour = $v['end_time'];
            if ($this->is_time_cross($add_hour, $end_hour, strtotime($add_time), strtotime($end_time))) {
                $orderStatus = 1;
            }
        }
        if ($orderStatus > 0) {
            return $this->returnErrorJson('当前已有预约，不可重复预约');
        }
        $user = $this->checkToken();
        if (empty($user)) {
            return $this->returnErrorJson('请先登录');
        }
        //订单 状态 订单状态0未开始，1进行中，2已结束，3已退款，4已取消，5已分账，6待付款
        //生成订单前将之前未支付的订单取消
        Order::where('user_id', $user['member_id'])->where('status', '=', 6)->update(['status' => 4]);
        $order_on = $this->orderOn();
        $data = array(
            'order_on' => $order_on,
            'store_id' => $store_id,
            'room_id' => $room_id,
            'add_time' => strtotime($add_time),
            'end_time' => strtotime($end_time),
            'price' => $package['price'],
            'hour' => $package['time'],
            'user_id' => $user['member_id'],
            'created_at' => date('Y-m-d H:i:s', time()),
            'order_type' => 0,
            'package_id' => $package_id,

        );
        // 查询是否重复
        $res = Order::insert($data);
        return $res ? $this->returnSuccessJson(compact('data')) : $this->returnErrorJson();
    }

    #[Api]
    #[PostMapping("info")]
    function info()
    {
        $order_on = $this->request->input('order_on', '');
        $order = Order::where('order_on', $order_on)->select('*')->first() ?: [];
        $order['add_time'] = date('Y-m-d H:i', $order['add_time']);
        $order['end_time'] = date('Y-m-d H:i', $order['end_time']);
        $fz = 1;
        $package = Package::where('package_id', $order['package_id'])
            ->select('*')
            ->first() ?: [];
        $store = Store::where('store_id', $order['store_id'])
            ->select('*')
            ->first() ?: [];
        $order['package_name'] = $package['name'];
        $order['head_url'] = $store['logo'];
        $order['store_name'] = $store['store_name'];
        $user = $this->checkToken();
        //余额记录  0  入账  1出账
        $balance0 = Db::table('balance_log')->where('member_id', $user['member_id'])->where('store_id', $order['store_id'])->where('type', 0)->sum('balance');
        $balance1 = Db::table('balance_log')->where('member_id', $user['member_id'])->where('store_id', $order['store_id'])->where('type', 1)->sum('balance');
        $user->balance = number_format($balance0 - $balance1, 2);

        return compact('order', 'fz', 'user');
    }

    #[Api]
    #[PostMapping("delete")]
    function delete()
    {
        $user = $this->checkToken();
        //订单 状态 订单状态0未开始，1进行中，2已结束，3已退款，4已取消，5已分账，6待付款
        $res = Order::where('user_id', $user['member_id'])->where('status', '=', 6)->update(['status' => 4]);
        return $res ? $this->returnSuccessJson(compact('res'), 'Success') : $this->returnErrorJson();
    }

    #[Api]
    #[PostMapping("payOrder")]
    function payOrder()
    {
        $user = $this->checkToken();
        $order_on = $this->request->input('order_on', '');
        $type = $this->request->input('type', '');
        $coupon_id = $this->request->input('coupon_id', '');
        $order = Order::where('order_on', $order_on)->select('*')->first() ?: [];
        //正常订单
        if ($order->order_type == 0) {
            switch ($type) {
                case 0:
                    //余额记录  0  入账  1出账
                    $balance0 = Db::table('balance_log')->where('member_id', $user['member_id'])->where('store_id', $order['store_id'])->where('type', 0)->sum('balance');
                    $balance1 = Db::table('balance_log')->where('member_id', $user['member_id'])->where('store_id', $order['store_id'])->where('type', 1)->sum('balance');
                    $balance = number_format($balance0 - $balance1, 2);
                    if ($balance < $order->price) {
                        return $this->returnErrorJson('余额不足');
                    }
                    $orderup = [];
                    $orderup['pay_type'] = 0;
                    $orderup['status'] = 0;
                    $orderup['pay_time'] = time();
                    $orderup['pay_price'] = 0;
                    $orderyz = Order::where('order_on', $order_on)->select('*')->first() ?: [];
                    if ($orderyz['status'] !== 6) {
                        return $this->returnErrorJson('订单状态无需支付');
                    }
                    if (Order::where('order_on', $order_on)->update($orderup)) {


                        $res = Db::table('balance_log')->insert(['member_id' => $user->member_id, 'store_id' => $order->store_id, 'type' => 1, 'balance' => $order->price]);
                    }
                    break;
                case 1:


                    return $this->returnSuccessJson(compact('order'));
                    break;
                case 2:
                    $orderup = [];
                    $orderup['pay_type'] = 2;
                    $orderup['status'] = 0;
                    $orderup['pay_time'] = time();
                    $orderup['pay_price'] = 0;
                    $orderyz = Order::where('order_on', $order_on)->select('*')->first() ?: [];
                    if ($orderyz['status'] !== 6) {
                        return $this->returnErrorJson('订单状态无需支付');
                    }
                    if (Order::where('order_on', $order_on)->update($orderup)) {
                        if ($coupon_id > 0) {
                            $status['status'] = 1;
                            $status['updated_at'] = date('Y-m-d H:i:s');
                            $res = CouponMember::where('coupon_member_id', $coupon_id)->update($status);
                        }
                    }
                    break;
            }
        }
        // 0.余额支付 1.微信支付   2.优惠卷直接抵扣   3.优惠卷+微信支付
        //订单 状态 订单状态0未开始，1进行中，2已结束，3已退款，4已取消，5已分账，6待付款

        //是加时订单
        if ($order->order_type == 1) {

        }

        return $res ? $this->returnSuccessJson(compact('res'), '支付成功') : $this->returnErrorJson('支付失败');
    }

    #[Api]
    #[PostMapping("UserOrder")]
    function UserOrder()
    {
        $user = $this->checkToken();
        $status = $this->request->input('status', '');

        if ($status !== '') {
            //订单 状态 订单状态0未开始，1进行中，2已结束，3已退款，4已取消，5已分账，6待付款
            if ($status == 1) {
                $where = [0];
            } elseif ($status == 2) {
                $where = [1];
            } elseif ($status == 3) {
                $where = [3];
            } elseif ($status == 4) {
                $where = [2, 4, 5];
            } elseif ($status == 0) {
                $where = [0, 1, 2];
            }
        }
        $res = Order::whereIn('status', $where)->where('user_id', $user['member_id'])->select('*')
            ->orderBy('created_at', 'desc')
            ->get()->toArray();
        $ressql = Order::whereIn('status', $where)->where('user_id', $user['member_id'])->select('*')
            ->orderBy('created_at', 'desc')
            ->toRawSql();
        foreach ($res as $k => $v) {
            $res[$k]['add_time'] = date('Y-m-d H:i', $v['add_time']);
            $res[$k]['end_time'] = date('Y-m-d H:i', $v['end_time']);
            $res[$k]['package_name'] = Db::table('package')->where('package_id', $v['package_id'])->value('name');
            $res[$k]['store_name'] = Db::table('store')->where('store_id', $v['store_id'])->value('store_name');
            $res[$k]['name'] = Db::table('room')->where('room_id', $v['room_id'])->value('name');
            $res[$k]['head_url'] = Db::table('room')->where('room_id', $v['room_id'])->value('image_url');

        }
        return compact('res', 'ressql');
    }

    #[Api]
    #[PostMapping("userOrderInfo")]
    function userOrderInfo()
    {
        $user = $this->checkToken();
        //订单 状态 订单状态0未开始，1进行中，2已结束，3已退款，4已取消，5已分账，6待付款
        $data = Order::whereIn('status', [0, 1])->where('user_id', $user['member_id'])
            ->where('add_time', '<', time() - 300)
            ->select('*')
            ->orderBy('created_at', 'asc')
            ->get()->toArray();
        foreach ($data as $k => $v) {
            $data[$k]['add_time'] = date('Y-m-d H:i', $v['add_time']);
            $data[$k]['end_time'] = date('Y-m-d H:i', $v['end_time']);
            $data[$k]['package_name'] = Db::table('package')->where('package_id', $v['package_id'])->value('name');
            $data[$k]['store_name'] = Db::table('store')->where('store_id', $v['store_id'])->value('store_name');
            $data[$k]['name'] = Db::table('room')->where('room_id', $v['room_id'])->value('name');
            $data[$k]['head_url'] = Db::table('room')->where('room_id', $v['room_id'])->value('image_url');

        }
        return compact('data');
    }

    /**
     * 管理员取消订单
     *
     */
    #[Api]
    #[PostMapping("ordercommand")]
    function ordercommand()
    {
        $order_on = $this->request->input('orderOn', '');
        $status = $this->request->input('status', '');
        //订单 状态 订单状态0未开始，1进行中，2已结束，3已退款，4已取消，5已分账，6待付款
        $order = Order::where('order_on', '=', $order_on)->select('*')->first() ?: [];
        if ($status == 2) {
            if (in_array($order->status, [1])) {
                $res = Order::where('order_on', '=', $order_on)->update(['status' => $status, 'updated_at' => date('Y-m-d H:i:s')]);
            } else {
                return $this->returnErrorJson('该订单状态不允许提前结束');
            }
        } elseif ($status == 3) {
            if (in_array($order->status, [0, 1, 2, 5])) {
                $res = Order::where('order_on', '=', $order_on)->update(['status' => 3, 'updated_at' => date('Y-m-d H:i:s')]);

            } else {
                return $this->returnErrorJson('该订单状态不允许退款');
            }
        }
        return $res ? $this->returnSuccessJson(compact('res'), '成功') : $this->returnErrorJson();
    }

    /**
     * 请求续单
     *
     */
    #[Api]
    #[PostMapping("renewal")]
    function renewal()
    {
        $order_on = $this->request->input('order_on', '');

        //订单 状态 订单状态0未开始，1进行中，2已结束，3已退款，4已取消，5已分账，6待付款
        $order = Order::where('order_on', '=', $order_on)->select('*')->first() ?: [];

        $where = [];
        $where[] = ['room_id', '=', $order->room_id];
        $packageids = Room::where($where)
            ->value('package_id');

        $renewal = Package::whereIn('package_id', $packageids)
            ->where('type', 1)
            ->select('*')
            ->orderBy('price', 'asc')
            ->get()->toArray();

        return compact('renewal', 'order', 'packageids');
    }

    /**
     * 创建续单订单
     *
     */
    #[Api]
    #[PostMapping("renewalOrder")]
    function renewalOrder()
    {
        $package_id = $this->request->input('package_id', '');
        $order_on = $this->request->input('order_on', '');
        // 查询当前是否预约

        $order = Order::where('order_on', '=', $order_on)->select('*')->first() ?: [];
        $package = Package::where('package_id', '=', $order->package_id)->select('*')->first() ?: [];
        // 判断是否重复预约
        $orderStatus = $this->repeat($order->room_id, $order->end_time, ($order->end_time) + $package->time * 3600);

        if ($orderStatus > 0) {
            return $this->returnErrorJson('当前已有预约');
        }
        $user = $this->checkToken();
        if (empty($user)) {
            return $this->returnErrorJson('请先登录');
        }
        //订单 状态 订单状态0未开始，1进行中，2已结束，3已退款，4已取消，5已分账，6待付款
        //生成订单前将之前未支付的订单取消
        Order::where('user_id', $user['member_id'])->where('status', '=', 6)->update(['status' => 4]);
        $order_onr = $this->orderOn();
        $data = array(
            'order_on' => $order_onr,
            'store_id' => $order->store_id,
            'room_id' => $order->room_id,
            'add_time' => $order->end_time,
            'end_time' => $order->end_time + $package->time * 3600,
            'price' => $package->price,
            'hour' => $package->time,
            'user_id' => $user->member_id,
            'created_at' => date('Y-m-d H:i:s', time()),
            'order_type' => 1,
            'package_id' => $package_id,

        );
        // 查询是否重复
        $res = Order::insert($data);
        return $res ? $this->returnSuccessJson(compact('data')) : $this->returnErrorJson();
    }


    /**
     * 查看是否预约
     * @param $room_id
     * @param $add_time
     * @param $end_time
     */
    public function repeat($room_id, $add_time, $end_time)
    {
        //订单 状态 订单状态0未开始，1进行中，2已结束，3已退款，4已取消，5已分账，6待付款
        $order = Order::where('room_id', $room_id)->where('status', 'in', [0, 1, 6])->select('*')->get()->toArray();;
        $status = array();
        if (count($order) > 0) {

            foreach ($order as $i => $v) {
                $add_hour = $v['add_time'];
                $end_hour = $v['end_time'];
                if ($this->is_time_cross($add_hour, $end_hour, $add_time, $end_time)) {
                    $status[] = '1';
                } else {
                    $status[] = '0';
                }
            }
        }
        if (in_array('1', $status, TRUE)) {
            $orderStatus = 1;
        } else {
            $orderStatus = 0;
        }
        return $orderStatus;
    }


}